﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent, Qt::WindowFlags f) :
    BaseEditor(parent,f),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    table=TD_TICKET;
    today=Today;
    selectDate=today;

    detectSpecMode();
    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);
    ui->listView->setEditTriggers(QListView::NoEditTriggers);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    updateDateList();
    updateView();
    createMenu();
    if(isSpecMode)
        showMaximized();
    else
        loadLocation();
    ui->ticket->setFocus();
}

Dialog::~Dialog()
{
    if(!isSpecMode)
        saveLocation();
    delete ui;
}

void Dialog::keyPressEvent(QKeyEvent *)
{
    /*
    switch (event->key()) {
    case Qt::Key_F5:
        updateView();
        break;
    case Qt::Key_F2:
        search();
        break;
    }
    */
}

void Dialog::detectSpecMode()
{
    isSpecMode=false;
    QSettings cfg(configFile,QSettings::IniFormat);
    if(cfg.value("Main/SpecMode").toInt() == 1)
        isSpecMode=true;
}

void Dialog::updateDateList()
{
    QStringList dateList;
    QSqlQuery query;
    query.exec(QString("select date from %1 group by date order by date DESC").arg(table));
    while (query.next()) {
        dateList.append(query.value(0).toString());
    }

    listModel->setStringList(dateList);
}

void Dialog::setHeaderData()
{
    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));   //date
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("时间"));   //time
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("单号"));   //ticket
}

void Dialog::generateMenu()
{
    // menu->addAction(QStringLiteral("更新视图(F5)"),this,&Dialog::updateView);
    // menu->addAction(QStringLiteral("导出"),this,&Dialog::exportData);
}

/*
void Dialog::exportData()
{
    QString path=QFileDialog::getExistingDirectory(this,QString("选择目录"));
    if(path.isEmpty())
        return;
    QString fileName=path + QString("/") + selectDate + ".csv";
    QFile file(fileName);
    if(file.open(QFile::WriteOnly | QFile::Text))
    {
        QTextStream text(&file);
        text << QStringLiteral("日期") << ","
             << QStringLiteral("时间") << ","
             << QStringLiteral("单号") << "\n";
        QSqlQuery query;
        query.exec(QString("select date,time,ticket from %1 where date='%2'")
                   .arg(table)
                   .arg(selectDate));
        while (query.next()) {
            text << query.value("date").toString() << ","
                 << query.value("time").toString() << ","
                 << query.value("ticket").toString() << "\n";
        }
        text.flush();
        file.close();
        QMessageBox::information(this,QStringLiteral("操作已完成"),
                                 QStringLiteral("数据已导出：\n") + fileName);
    }
}
*/

void Dialog::do_updateView(const QString &date)
{
    model->setTable(table);
    model->setFilter(QString("date='%1'").arg(date));
    model->select();

    int count=model->rowCount();
    if(count > 0)
    {
        QString numberStr=QString::number(count);
        ui->status->setText(QStringLiteral("当前数量：") + numberStr);
    }
    setHeaderData();
}

void Dialog::updateView()
{
    do_updateView(today);
}

bool Dialog::addItem(const QString &ticket)
{
    today=CurrentDate;

    QSqlQuery query;
    query.prepare(QString("insert into %1 (date,time,ticket) values (?,?,?)")
                  .arg(table));
    query.addBindValue(today);
    query.addBindValue(CurrentTime);
    query.addBindValue(ticket);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void Dialog::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
        do_updateView(index.data().toString());
}

void Dialog::on_ticket_returnPressed()
{
    QString ticket=ui->ticket->text().trimmed();
    if(ticket.isEmpty())
        return;

    if(history.contains(ticket))
    {
        ui->ticket->clear();
        return;
    }

    if(!control_filter(ticket))
    {
        ui->ticket->clear();
        return;
    }

    if(addItem(ticket))
    {
        history.append(ticket);
        if(!listModel->stringList().contains(today))
            updateDateList();

        ui->ticket->clear();
        updateView();
    }
    else
        MESSAGE_CANNOT_SUBMIT
}

void Dialog::on_search_returnPressed()
{
    // QString keyword=QInputDialog::getText(this,QStringLiteral("输入要查询的单号"),QStringLiteral("单号"));
    QString keyword=ui->search->text().trimmed();
    if(!keyword.isEmpty())
    {
        model->setFilter(QString("ticket like '%%1%'")
                         .arg(keyword));
        model->select();
        setHeaderData();
    }
}
